package com.team.instantsharing.home

import com.team.instantsharing.dto.LoginResponse;
import com.team.instantsharing.dto.User
import com.team.instantsharing.ultils.Constant;
import com.team.instantsharing.ultils.FileConvert;
import com.team.instantsharing.ultils.RequestHeader;
import com.team.instantsharing.ultils.ServiceRequest;

import grails.plugin.cookie.CookieService;

import org.springframework.http.HttpEntity
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestTemplate

class HomeController {

	CookieService cookieService;
	
    def index() {
		String sessionEmail = session.userEmail;
		String rememberToken = cookieService.getCookie('remember_me_cookie');
		if(sessionEmail != null && sessionEmail.length() != 0){
			redirect controller:'manage', action: 'index'
		}
		else if(rememberToken != null && rememberToken != ""){
			RestTemplate restTemplate = new RestTemplate();
			HttpEntity entity = new HttpEntity(RequestHeader.getDefaultHeader());
			LoginResponse loginResponse = restTemplate.exchange(Constant.SERVICE_URL + ServiceRequest.LOGIN_WITH_REMEMBER_TOKEN + Constant.SUFFIX + rememberToken, HttpMethod.GET, entity, LoginResponse.class).body;
			
			if (loginResponse.getUserId() > 0){
				//Put Session
				session.userName = loginResponse.getUserName()
				session.userId = loginResponse.getUserId()
				session.userToken = loginResponse.getUserToken();
				session.userEmail = loginResponse.getUserEmail()
				session.availableCapacity = loginResponse.getAvailableCapacity();
				session.usedCapacity = loginResponse.getUsedCapacity();
				session.availableCapacityString = FileConvert.getDocumentCapacityString(loginResponse.getAvailableCapacity());
				session.usedCapacityString = FileConvert.getDocumentCapacityString(loginResponse.getUsedCapacity());
				
				redirect controller:'manage', action: 'index'
			}
		}
	}
}
